var designClass = "design_class", hideClass = "hide_class", browseClass = "browse_class", addClass = "add_class", editClass = "edit_class";
var upWindow = window.parent.frames["zwIframe"];
if (!upWindow) {
    upWindow = window.parent.frames["componentDiv"].frames["zwIframe"];
}
// 关闭自定义扩张控件弹出窗口
function fy_dialog_close() {
    window.parent.$(".layui-layer-iframe").parent().find(".layui-layer-close").trigger(
            "click");
}

function getUpFields(name) {
    return upWindow.$("[validate*='name:\"" + name + "\"']");
}

function getUpFieldsByFieldval(name) {
    return upWindow.$("[fieldval*='displayName:\"" + name + "\"']");
}

function getUpFieldValueByName(name, index) {
    return getUpFieldValue(getUpFieldsByFieldval(name).eq(index ? index : 0));
}

function getUpFieldValue(field) {
    var fieldVal = field.attr("fieldVal");
    var editTag = field.hasClass(editClass);
    var browseTag = field.hasClass(browseClass);
    var addTag = field.hasClass(addClass);
    if (fieldVal != null && typeof (fieldVal) != 'undefined') {
        fieldVal = eval("(" + fieldVal + ")");
    } else {
        return null;
    }
    var obj = new Object();
    obj.displayName = fieldVal.displayName;
    obj.name = fieldVal.name;
    var tag = true;
    switch (fieldVal.inputType) {
        case "text":
        case "textarea":

            if (editTag) {
                obj.value = field.find("#" + fieldVal.name).val();
            } else if (browseTag) {
                obj.value = fieldVal.value;
            } else if (addTag) {
                obj.value = field.find("#" + fieldVal.name).val();
            }
            break;
        case "checkbox":
            if (editTag) {
                obj.value = field.find("#" + fieldVal.name).val();
            } else if (browseTag) {
                obj.value = field.find("#" + fieldVal.name).val();
            }
            break;
        case "radio":
            if (editTag) {
                obj.value = field.find(":radio:checked").attr("val4cal");
            } else if (browseTag) {
                obj.value = field.find(":radio:checked").attr("val4cal");
            }
            break;
        case "select":
            if (editTag) {
                obj.value = field.find("#" + fieldVal.name + " option:selected")
                        .attr("val4cal");
            } else if (browseTag) {
                obj.value = field.find("#" + fieldVal.name).attr("val4cal");
            }
            break;
        case "date":
            if (editTag) {
                obj.value = field.find("#" + fieldVal.name).val();
                if (obj.value != "") {
                    obj.value = obj.value + " 00:00";
                }
            } else if (browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "datetime":
            if (editTag) {
                obj.value = field.find("#" + fieldVal.name).val();
            } else if (browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "flowdealoption":
            if (editTag) {
                obj.value = fieldVal.value;
            } else if (browseTag) {
                obj.value = fieldVal.value;
            } else if (addTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "lable":
            if (editTag) {
                obj.value = fieldVal.value;
            } else if (browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "relationform":
            if (editTag) {
                obj.value = fieldVal.value;
            } else if (browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "relation":
            if (editTag || browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "project":
            if (editTag) {
                obj.value = field.find("#" + fieldVal.name).val();
            } else if (browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "member":
        case "multimember":
        case "account":
        case "multiaccount":
        case "department":
        case "multidepartment":
        case "post":
        case "multipost":
        case "level":
        case "multilevel":
            if (editTag) {
                obj.value = field.find("#" + fieldVal.name + "_txt").val();
            } else if (browseTag) {
                obj.value = field.find("#" + fieldVal.name).text();
            }
            break;
        case "attachment":
        case "image":
        case "document":
            if (editTag || browseTag) {
                var attNames = "";
                var tempField = field.find("#" + fieldVal.name);
                var tempFileId = "";
                if (tempField[0].tagName.toLowerCase() == "input") {
                    tempFileId = tempField.val();
                } else if (tempField[0].tagName.toLowerCase() == "span") {
                    tempFileId = tempField[0].innerHTML;
                }
                var atts = upWindow.getAttBySubreference(tempFileId);
                for (var j = 0; j < atts.length; j++) {
                    attNames += atts[j].filename + ",";
                }
                if (attNames != "") {
                    attNames = attNames.substr(0, attNames.length - 1);
                }
                obj.value = attNames;
            }
            break;
        case "outwrite":
            if (editTag || browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "externalwrite-ahead":
            if (editTag || browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "exchangetask":
            if (editTag || browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "querytask":
            if (editTag || browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        default:
            tag = false;
    }
    if (obj.value != undefined) {
        obj.value = obj.value.replace("\r\n", ";");
        obj.value = obj.value.replace("\n", ";");
    }
    return obj;
}

function setUpFieldValue(name, value) {
    upWindow.$("[fieldval*='displayName:\"" + name + "\"']").find("input").val(
            value);
    upWindow.$("[fieldval*='displayName:\"" + name + "\"']").find("input")
            .trigger("blur");
}

function setUpFieldValue2(field, value, displayValue, index) {

    try {

        var fieldVal = field.attr("fieldVal");
        var editTag = field.hasClass(editClass);
        var addTag = field.hasClass(addClass);
        value = (value);
        displayValue = displayValue ? (displayValue) : displayValue;
        if (fieldVal != null && typeof (fieldVal) != 'undefined') {
            fieldVal = eval("(" + fieldVal + ")");
        } else {
            return null;
        }
        var tag = true;
        switch (fieldVal.inputType) {
            case "text":
            case "textarea":
                if (editTag) {
                    var inField = field.find("#" + fieldVal.name);
                    inField.val(value);
                    inField.trigger("blur");
                } else if (addTag) {
                    var inField = field.find("#" + fieldVal.name);
                    inField.val(value);
                    inField.trigger("blur");
                }
                break;
            case "checkbox":
                if (editTag) {
                    field.find("#" + fieldVal.name).attr("checked", true);
                    field.find("#" + fieldVal.name).trigger("click");
                }
                break;
            case "radio":
                if (editTag) {
                    field.find(":radio").eq(index).attr("checked", true);
                    field.find(":radio").eq(index).trigger("click");
                }
                break;
            case "select":
                if (editTag) {
                    var options = field.find("#" + fieldVal.name + " option");
                    for (var k = 0; k < options.length; k++) {
                        if (options.eq(k).text() == value)
                            options.eq(k).attr("selected", true);
                    }
                    field.find("#" + fieldVal.name).trigger("change");
                }
                break;
            case "date":
                if (editTag) {
                    field.find("#" + fieldVal.name).val(value);
                    field.find("#" + fieldVal.name).trigger("blur");
                }
                break;
            case "datetime":
                if (editTag) {
                    field.find("#" + fieldVal.name).val(value);
                    field.find("#" + fieldVal.name).trigger("blur");
                }
                break;
            case "member":
            case "multimember":
            case "account":
            case "multiaccount":
            case "department":
            case "multidepartment":
            case "post":
            case "multipost":
            case "level":
            case "multilevel":
                if (editTag) {
                    // alert(editTag);
                    field.find("#" + fieldVal.name).val(value);
                }
                break;
        }
    } catch (e) {
        // TODO: handle exception
    }
}
// 添加或者删除行
function addOrDelRepeat(name, newLength) {
    var fields = getUpFieldsByFieldval(name);
    var oldLength = fields.length;
    var tbody = getUpFieldsByFieldval(name).eq(0).parent();
    while (!tbody.is("tbody")) {
        tbody = tbody.parent();
    }
    for (var i = 0, length = Math.abs(newLength - oldLength); i < length; i++) {
        if (newLength > oldLength) {
            upWindow.fy_addEmpty(tbody.children().last());
        } else {
            upWindow.fy_delCurrentRepeat(tbody.children().last());
        }
    }
    upWindow.fy_setReadonly();
}
function $(name) {
    return document.getElementsByName(name);
}

var inputMap = {
    "原供应商名称": "oldSupplierName",
    "原供应商编码": "oldSupplierCode",
    "目标供应商名称": "newSupplierName",
    "目标供应商编码": "newSupplierCode",
    "备注": "remark"
};

var notAllowBlank = {
    oldSupplierName: "原供应商名称",
    oldSupplierCode: "原供应商编码",
    newSupplierName: "目标供应商名称",
    newSupplierCode: "目标供应商编码",
    newAddress: "目标供应商地点",
    oldAddress: "原供应商地点"
}

function resetValues() {
    $("resetForm")[0].reset();
}

/**
 * 全角转半角，小写转大写
 * 
 * @param {}
 *            field
 */
function replaceIllegalCharacter(field) {
    var charlist = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    charlist += "abcdefghijklmnopqrstuvwxyz";
    charlist += "0123456789";
    charlist += " `~!@#$%^&*()_+-={}|[]\:\\\";'<>?,./";// 半角空格

    var providerName = field.value;
    var result = "";
    for (var i = 0; i < providerName.length; i++) {
        var c1 = providerName.charAt(i);
        var c2 = providerName.charCodeAt(i);
        if ("　" == c1) {
            result += " ";
        } else if ("，" == c1) {
            result += ",";
        } else if ("。" == c1) {
            result += ".";
        } else {
            if (charlist.indexOf(String.fromCharCode(c2 - 65248)) > -1) {
                result += String.fromCharCode(c2 - 65248);
            } else {
                result += c1;
            }
        }
    }
    field.value = result.toUpperCase();
}

function supplierCodeValueChange(field, supplierName, address, operate) {
    setButtonDisabled(true);
    replaceIllegalCharacter(field);
    getParentTR(field).parentNode.getElementsByTagName("select")[operate - 1].options.length = 0;
    var supplierCode = field.value;
    if (supplierCode.replace(/ /g, "") == "") {
        var inputs = getParentTR(field).parentNode
                .getElementsByTagName("input");
        for (var i = 0; i < inputs.length; i++) {
            if (inputs[i].name == supplierName) {
                inputs[i].value = "";
                break;
            }
        }
        setButtonDisabled(false);
    } else {
        var inputs = getParentTR(field).parentNode
                .getElementsByTagName("input");
        for (var i = 0; i < inputs.length; i++) {
            if (inputs[i].name == supplierName) {
                inputs[i].value = "";
                break;
            }
        }
        _ajax(
                "../oa2uapController.do?method=erpMergerOperate&code="
                + supplierCode + '&ou_id=' + $("corpSelect")[0].value
                + '&operate=' + operate,
                function (data) {
                    var parentNode = getParentTR(field).parentNode;
                    var inputs = parentNode.getElementsByTagName("input");
                    for (var i = 0; i < inputs.length; i++) {
                        if (inputs[i].name == supplierName) {
                            inputs[i].value = data.name;
                        }

                    }
                    for (var j = 0; j < data.address.length; j++) {
                        var option = document.createElement
                        parentNode.getElementsByTagName("select")[operate - 1].options
                                .add(createOption(data.address[j], j));
                        parentNode.getElementsByTagName("select")[operate - 1].value = 0;
                    }
                });
    }
}
/**
 * 输入原供应商编码，查询原供应商名称
 * 
 * @param {}
 *            field
 */
function oldSupplierCodeValueChange(field) {
    supplierCodeValueChange(field, "oldSupplierName", "oldAddress", 1);
}
function newSupplierCodeValueChange(field) {
    supplierCodeValueChange(field, "newSupplierName", "newAddress", 2);
}

function setButtonDisabled(disabled) {
    document.getElementById("ok_button").disabled = disabled;
}

function writeToForm() {
    // var supplierNames = $2("原供应商名称");
    var supplierNameNodes = $("oldSupplierName");
    // var oldLength = supplierNames.length;
    addOrDelRepeat("原供应商名称", supplierNameNodes.length);
    // var upTR = getParentTR(supplierNames[supplierNames.length - 1]);
    // for (var i = 0; i < supplierNameNodes.length; i++) {
    // upTR.id = "oper";
    // window.dialogArguments.addEmpty();
    // }
    //
    // for (var i = 0; i < oldLength; i++) {
    // getParentTR($2("原供应商名称")[0]).id = "oper";
    // window.dialogArguments.del();
    // }
    for (var i = 0; i < supplierNameNodes.length; i++) {
        for (var key in inputMap) {
            setUpFieldValue2(getUpFieldsByFieldval(key).eq(i),
                    $(inputMap[key])[i].value);
        }
        // $2("序号")[i].value = i + 1;
        setUpFieldValue2(
                getUpFieldsByFieldval("目标供应商地点").eq(i),
                $("newAddress")[i].options[$("newAddress")[i].selectedIndex].text);
        setUpFieldValue2(
                getUpFieldsByFieldval("原供应商地点").eq(i),
                $("oldAddress")[i].options[$("oldAddress")[i].selectedIndex].text);
    }

    setUpFieldValue2(getUpFieldsByFieldval("OU_ID").eq(0),
            $("corpSelect")[0].value);
    setUpFieldValue2(getUpFieldsByFieldval("供应制造部").eq(0),
            ou_idMap[$("corpSelect")[0].value]);

    fy_dialog_close();
}

/**
 * 将填写的内容写入到表单
 */
function okButtonClick() {
    setButtonDisabled(true);
    var oldSupplierCodes = $("oldSupplierCode");
    for (var i = 0; i < oldSupplierCodes.length; i++) {
        for (var key in notAllowBlank) {
            if (!$(key)[i].value || $(key)[i].value == "") {
                alert(notAllowBlank[key] + "不能为空");
                return setButtonDisabled(false);
            } else {
                for (var j = i; j < oldSupplierCodes.length; j++) {
                    if (i != j
                            && $("oldSupplierCode")[i].value == $("oldSupplierCode")[j].value
                            && $("oldAddress")[i].options[$("oldAddress")[i].selectedIndex].text == $("oldAddress")[j].options[$("oldAddress")[j].selectedIndex].text) {
                        alert("第" + (i + 1) + "和第" + (j + 1) + "的原供应商和原供应商地点相同");
                        return setButtonDisabled(false);
                    }
                }
            }
        }

        if (oldSupplierCodes[i].value == $("newSupplierCode")[i].value) {
            alert("目标供应商不能和原供应商相同。");
            return setButtonDisabled(false);
        }
    }
    var strArray = [];
    for (var i = 0; i < oldSupplierCodes.length; i++) {
        strArray.push("&code=");
        strArray.push(oldSupplierCodes[i].value);
        strArray.push("&site=");
        strArray
                .push(encodeURIComponent($("oldAddress")[i].options[$("oldAddress")[i].selectedIndex].text));
    }

    _ajax("../oa2uapController.do?method=erpMergerOperate&operate=4&corp="
            + $("corpSelect")[0].value + strArray.join(""), function (data) {
        writeToForm();
    }, true);

}
function _ajax(url, operator, isPost) {
    document.getElementById("lodingDiv").style.height =
            document.body.clientHeight + "px";
    document.getElementById("lodingDiv").style.display = '';
    var xmlhttp = null;
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera,
        xmlhttp = new XMLHttpRequest();
    } else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4) {
            if (xmlhttp.status == 200) {
                text = xmlhttp.responseText;
                if (text == 1) {
                    alert("供应商编码不能为空");
                } else if (text == 2) {
                    alert("用户还未登陆，或者已掉线");
                } else if (text == 3) {
                    alert("供应制造部ID不能为空。");
                } else if (text == 4) {
                    alert("常数不能为空");
                } else if (text == 5) {
                    alert("供应商名称不能为空");
                } else {
                    var data = eval("(" + text + ")");
                    if (data.success)
                        operator(data);
                    else
                        alert(data.data);
                }
            } else {
                alert("连接服务器异常");
            }
            document.getElementById("lodingDiv").style.display
                    = 'none';
            try {
                setButtonDisabled(false);
            } catch (e) {
            }
        }
    };
    xmlhttp.open(isPost ? "post" : "get", url + "&temp=" + Math.random(), true);
    xmlhttp.send();
}

window.onload = function () {

    for (var key in ou_idMap) {
        $("corpSelect")[0].options.add(createOption(ou_idMap[key], key));
    }
    var OU_ID = getUpFieldValue(getUpFieldsByFieldval("OU_ID").eq(0)).value;
    if (OU_ID != "") {
        $("corpSelect")[0].value = getUpFieldValue(getUpFieldsByFieldval("OU_ID").eq(0)).value;
    } else {
        $("corpSelect")[0].options[0].selected = true;
    }
    /**
     * 界面初始化
     */
    /**
     * 填写新建表单
     */
    // 重复表初始化
    var firstTR = getParentTR(document.getElementById("repeatTable").getElementsByTagName("TR")[0]);
    var repeatOperator = new RepeateTableOperator(firstTR.parentNode);

    repeatOperator.setAfterAddTrOperate(function (trNode) {
        trNode.getElementsByTagName("select")[0].options.length = 0;
        trNode.getElementsByTagName("select")[1].options.length = 0;
    });

    repeatOperator.addListeners(firstTR);

    // 把表单的内容复制到填写界面的对应的输入框
    var supplierNames = getUpFieldsByFieldval("原供应商编码");
    repeatOperator.addEmptyTR(firstTR, supplierNames.length - 1);
    for (var i = 0; i < supplierNames.length; i++) {
        for (var key in inputMap) {
            $(inputMap[key])[i].value = getUpFieldValue(getUpFieldsByFieldval(key).eq(i)).value;
        }
        var newAddress = getUpFieldValue(getUpFieldsByFieldval("目标供应商地点").eq(0)).value;
        if (newAddress && newAddress != "") {
            $("newAddress")[i].options
                    .add(createOption(newAddress, 0));
            $("newAddress")[i].value = 0;
        }

        var oldAddress = getUpFieldValue(getUpFieldsByFieldval("原供应商地点").eq(0)).value;

        if (oldAddress && oldAddress != "") {
            $("oldAddress")[i].options
                    .add(createOption(oldAddress, 0));
            $("oldAddress")[i].value = 0;
        }
    }
};
function createOption(text, value) {
    var op = document.createElement("option");
    op.value = value;
    op.text = text;
    return op;
}